package com.lagou.niancheng.work2.consumer;


import com.lagou.niancheng.work2.api.Work2DubboApi;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ConsumerApplication {

    public static void main(String[] args) {
        // 并发因子，保证方法一分钟内达到2000，则我们先假设一个方法同步调用最大耗时100ms，则1s内可以调用10次
        // 一分钟可以调用600次，则并发数达到3-4即可满足1分钟内2000次调用的要求
        int concurrentFactor = 3;
        // 定义三个方法调用线程池
        ThreadPoolExecutor threadPool1 = new ThreadPoolExecutor(concurrentFactor, concurrentFactor, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new DefaultThreadFactory("method1"));
        ThreadPoolExecutor threadPool2 = new ThreadPoolExecutor(concurrentFactor, concurrentFactor, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new DefaultThreadFactory("method2"));
        ThreadPoolExecutor threadPool3 = new ThreadPoolExecutor(concurrentFactor, concurrentFactor, 0, TimeUnit.SECONDS, new SynchronousQueue<>(), new DefaultThreadFactory("method3"));
        // 创建spring容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:consumer.xml");
        context.start();
        // 获取到rpc接口
        Work2DubboApi work2DubboApi = context.getBean(Work2DubboApi.class);

        // 方法1调用
        for (int i = 0; i < concurrentFactor; i++) {
            threadPool1.execute(() -> {
                while (true) {
                    work2DubboApi.method1();
                }
            });
        }

        // 方法2调用
        for (int i = 0; i < concurrentFactor; i++) {
            threadPool2.execute(() -> {
                while (true) {
                    work2DubboApi.method2();
                }
            });
        }

        // 方法3调用
        for (int i = 0; i < concurrentFactor; i++) {
            threadPool3.execute(() -> {
                while (true) {
                    work2DubboApi.method3();
                }
            });
        }


    }

}
